<template>
  <div class="home-page">
    <!-- Header -->
    <div class="home-header">
      <div class="user-greeting">
        <div class="avatar">
          <van-image :src="userStore.userInfo?.avatar || '/default-avatar.png'" round width="40" height="40"
            fit="cover" />
        </div>
        <div class="greeting-text">
          <div class="welcome">Welcome back,</div>
          <div class="username">{{ userStore.userInfo?.username || 'User' }}</div>
        </div>
      </div>
      <div class="header-actions">
        <van-icon name="bell-o" size="24" @click="showNotifications" />
        <van-icon name="search" size="24" @click="showSearch" />
      </div>
    </div>

    <!-- Daily Challenge Card -->
    <div class="daily-challenge-card" v-if="todayChallenge">
      <div class="card-header">
        <h3>Today's Challenge</h3>
        <van-tag :type="challengeTypeColor(todayChallenge.category) as any">{{ todayChallenge.category }}</van-tag>
      </div>
      <div class="challenge-content">
        <h4>{{ todayChallenge.title }}</h4>
        <p>{{ todayChallenge.description }}</p>
        <div class="challenge-progress">
          <van-progress :percentage="challengeProgress" stroke-width="6" />
          <span class="progress-text">{{ challengeProgress }}% Complete</span>
        </div>
      </div>
      <div class="challenge-actions">
        <van-button type="primary" size="small" :disabled="todayChallenge.is_completed" @click="startChallenge">
          {{ todayChallenge.is_completed ? 'Completed' : 'Start Challenge' }}
        </van-button>
      </div>
    </div>

    <!-- Quick Actions -->
    <div class="quick-actions">
      <h3 class="section-title">Quick Actions</h3>
      <div class="actions-grid">
        <div class="action-item" @click="startTraining">
          <div class="action-icon">
            <van-icon name="play-circle-o" size="32" color="#667eea" />
          </div>
          <div class="action-text">
            <div class="action-title">Start Training</div>
            <div class="action-subtitle">Practice with AI characters</div>
          </div>
        </div>

        <div class="action-item" @click="viewCommunity">
          <div class="action-icon">
            <van-icon name="friends-o" size="32" color="#4ecdc4" />
          </div>
          <div class="action-text">
            <div class="action-title">Community</div>
            <div class="action-subtitle">Share and learn together</div>
          </div>
        </div>

        <div class="action-item" @click="viewProgress">
          <div class="action-icon">
            <van-icon name="chart-trending-o" size="32" color="#45b7d1" />
          </div>
          <div class="action-text">
            <div class="action-title">My Progress</div>
            <div class="action-subtitle">Track your improvement</div>
          </div>
        </div>

        <div class="action-item" @click="viewAchievements">
          <div class="action-icon">
            <van-icon name="medal-o" size="32" color="#f39c12" />
          </div>
          <div class="action-text">
            <div class="action-title">Achievements</div>
            <div class="action-subtitle">View your badges</div>
          </div>
        </div>
      </div>
    </div>

    <!-- Recent Activity -->
    <div class="recent-activity">
      <div class="section-header">
        <h3 class="section-title">Recent Activity</h3>
        <van-button type="primary" plain size="mini" @click="viewAllActivity">
          View All
        </van-button>
      </div>

      <div class="activity-list" v-if="recentActivities.length > 0">
        <div class="activity-item" v-for="activity in recentActivities" :key="activity.id"
          @click="viewActivityDetail(activity)">
          <div class="activity-icon">
            <van-icon :name="getActivityIcon(activity.type)" size="20" />
          </div>
          <div class="activity-content">
            <div class="activity-title">{{ activity.title }}</div>
            <div class="activity-time">{{ formatTime(activity.createdAt) }}</div>
          </div>
          <div class="activity-arrow">
            <van-icon name="arrow" size="16" />
          </div>
        </div>
      </div>

      <van-empty v-else description="No recent activity" />
    </div>

    <!-- Social Energy Station -->
    <div class="social-energy" v-if="energyContent">
      <h3 class="section-title">Social Energy Station</h3>
      <div class="energy-card">
        <div class="energy-header">
          <h4>{{ energyContent.title }}</h4>
          <van-tag type="success">{{ energyContent.type }}</van-tag>
        </div>
        <div class="energy-content">
          <p>{{ energyContent.content }}</p>
        </div>
        <div class="energy-actions">
          <van-button size="small" @click="likeEnergyContent">
            <van-icon name="good-job-o" /> {{ energyContent.likesCount }}
          </van-button>
          <van-button size="small" @click="shareEnergyContent">
            <van-icon name="share-o" /> Share
          </van-button>
        </div>
      </div>
    </div>

    <!-- Search Dialog -->
    <van-dialog v-model:show="showSearchDialog" title="Search Social Dojo" show-cancel-button @confirm="performSearch">
      <van-field v-model="searchQuery" placeholder="Search for training, community, challenges..." clearable
        @keyup.enter="performSearch" />
    </van-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { showToast } from 'vant'
import { useUserStore } from '@/stores/user'
import { dailyChallengeApi, type DailyChallenge } from '@/api/dailyChallenge'

const router = useRouter()
const userStore = useUserStore()

const todayChallenge = ref<DailyChallenge | null>(null)
const energyContent = ref<any>(null)
const recentActivities = ref<any[]>([])
const loading = ref(false)

const challengeProgress = computed(() => {
  if (!todayChallenge.value) return 0
  return todayChallenge.value.is_completed ? 100 : 0
})

const challengeTypeColor = (type: string) => {
  const colors: Record<string, 'primary' | 'success' | 'warning' | 'danger' | 'default'> = {
    training: 'primary',
    social: 'success',
    learning: 'warning',
    sharing: 'danger'
  }
  return colors[type] || 'default'
}

const formatTime = (timestamp: string) => {
  const now = Date.now()
  const time = new Date(timestamp).getTime()
  const diff = now - time
  const hours = Math.floor(diff / (1000 * 60 * 60))

  if (hours < 1) {
    return 'Just now'
  } else if (hours < 24) {
    return `${hours}h ago`
  } else {
    const days = Math.floor(hours / 24)
    return `${days}d ago`
  }
}

const getActivityIcon = (type: string) => {
  const icons: Record<string, string> = {
    training: 'play-circle-o',
    achievement: 'medal-o',
    social: 'friends-o',
    challenge: 'flag-o'
  }
  return icons[type] || 'info-o'
}

const showNotifications = () => {
  router.push('/notifications')
}

const showSearchDialog = ref(false)
const searchQuery = ref('')

const showSearch = () => {
  showSearchDialog.value = true
}

const performSearch = () => {
  if (!searchQuery.value.trim()) {
    showToast('Please enter a search term')
    return
  }

  // Navigate to appropriate section based on search
  const query = searchQuery.value.toLowerCase()

  if (query.includes('training') || query.includes('practice') || query.includes('session')) {
    router.push('/training')
  } else if (query.includes('community') || query.includes('post') || query.includes('share')) {
    router.push('/community')
  } else if (query.includes('challenge') || query.includes('daily')) {
    router.push('/motivation/daily-challenges')
  } else if (query.includes('achievement') || query.includes('badge')) {
    router.push('/achievements')
  } else {
    // General search - go to training page
    router.push('/training')
  }

  showSearchDialog.value = false
  searchQuery.value = ''
}

const startChallenge = () => {
  if (todayChallenge.value && !todayChallenge.value.is_completed) {
    router.push(`/challenge/${todayChallenge.value.id}`)
  }
}

const startTraining = () => {
  router.push('/training')
}

const viewCommunity = () => {
  router.push('/community')
}

const viewProgress = () => {
  router.push('/profile/progress')
}

const viewAchievements = () => {
  router.push('/profile/achievements')
}

const viewAllActivity = () => {
  router.push('/profile/activity')
}

const viewActivityDetail = (activity: any) => {
  showToast(`Activity: ${activity.title}`)
}

const likeEnergyContent = () => {
  if (energyContent.value) {
    energyContent.value.likesCount++
    showToast('Liked!')
  }
}

const shareEnergyContent = async () => {
  if (!energyContent.value) {
    showToast('No content to share')
    return
  }

  try {
    const shareData = {
      title: energyContent.value.title,
      text: energyContent.value.content,
      url: `${window.location.origin}/community/post/${energyContent.value.id}`
    }

    if (navigator.share) {
      await navigator.share(shareData)
      showToast('Shared successfully!')
    } else {
      await navigator.clipboard.writeText(shareData.url)
      showToast('Link copied to clipboard!')
    }
  } catch (error) {
    if (error instanceof Error && error.name !== 'AbortError') {
      showToast('Failed to share content')
    }
  }
}

// Load data from API
const loadHomeData = async () => {
  try {
    loading.value = true

    // Load today's challenge
    const challengeResponse = await dailyChallengeApi.getTodayChallenge()
    if (challengeResponse.success && challengeResponse.data) {
      todayChallenge.value = challengeResponse.data
    }

    // Mock social energy content (would be replaced with real API)
    energyContent.value = {
      id: 1,
      title: "Today's Motivation",
      content: "Every conversation is a chance to learn something new about yourself and others.",
      author: "Social Dojo Team",
      likesCount: 42,
      isLiked: false
    }

    // Mock recent activities (would be replaced with real API)
    recentActivities.value = [
      {
        id: 1,
        type: 'training',
        title: 'Completed conversation with Emma',
        createdAt: new Date(Date.now() - 2 * 60 * 60 * 1000).toISOString()
      },
      {
        id: 2,
        type: 'achievement',
        title: 'Earned "Ice Breaker" badge',
        createdAt: new Date(Date.now() - 5 * 60 * 60 * 1000).toISOString()
      },
      {
        id: 3,
        type: 'social',
        title: 'Shared training result',
        createdAt: new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString()
      }
    ]
  } catch (error) {
    console.error('Failed to load home data:', error)
    showToast('Failed to load data')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  loadHomeData()
})
</script>

<style lang="scss" scoped>
.home-page {
  min-height: 100vh;
  background: $background-color;
}

.home-header {
  background: $white;
  padding: $spacing-md;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: $box-shadow-light;

  .user-greeting {
    display: flex;
    align-items: center;
    gap: $spacing-sm;

    .greeting-text {
      .welcome {
        font-size: $font-size-sm;
        color: $text-color-3;
      }

      .username {
        font-size: $font-size-lg;
        font-weight: $font-weight-medium;
        color: $text-color;
      }
    }
  }

  .header-actions {
    display: flex;
    gap: $spacing-md;

    .van-icon {
      color: $text-color-3;
      cursor: pointer;

      &:hover {
        color: $primary-color;
      }
    }
  }
}

.daily-challenge-card {
  margin: $spacing-md;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: $border-radius-lg;
  padding: $spacing-lg;
  color: $white;

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: $spacing-md;

    h3 {
      font-size: $font-size-lg;
      font-weight: $font-weight-medium;
    }
  }

  .challenge-content {
    margin-bottom: $spacing-md;

    h4 {
      font-size: $font-size-md;
      margin-bottom: $spacing-xs;
    }

    p {
      font-size: $font-size-sm;
      opacity: 0.9;
      margin-bottom: $spacing-md;
    }

    .challenge-progress {
      display: flex;
      align-items: center;
      gap: $spacing-sm;

      .progress-text {
        font-size: $font-size-xs;
        opacity: 0.8;
      }
    }
  }
}

.section-title {
  font-size: $font-size-lg;
  font-weight: $font-weight-medium;
  color: $text-color;
  margin-bottom: $spacing-md;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: $spacing-md;
}

.quick-actions {
  padding: $spacing-md;

  .actions-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: $spacing-md;

    .action-item {
      background: $white;
      border-radius: $border-radius-lg;
      padding: $spacing-md;
      display: flex;
      align-items: center;
      gap: $spacing-sm;
      box-shadow: $box-shadow-light;
      cursor: pointer;
      transition: transform 0.2s ease;

      &:active {
        transform: scale(0.98);
      }

      .action-text {
        .action-title {
          font-size: $font-size-sm;
          font-weight: $font-weight-medium;
          color: $text-color;
        }

        .action-subtitle {
          font-size: $font-size-xs;
          color: $text-color-3;
        }
      }
    }
  }
}

.recent-activity {
  padding: $spacing-md;

  .activity-list {
    background: $white;
    border-radius: $border-radius-lg;
    overflow: hidden;

    .activity-item {
      display: flex;
      align-items: center;
      padding: $spacing-md;
      border-bottom: 1px solid $border-color-light;
      cursor: pointer;

      &:last-child {
        border-bottom: none;
      }

      &:active {
        background: $gray-1;
      }

      .activity-icon {
        width: 40px;
        height: 40px;
        border-radius: 50%;
        background: $gray-2;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: $spacing-sm;
      }

      .activity-content {
        flex: 1;

        .activity-title {
          font-size: $font-size-sm;
          color: $text-color;
          margin-bottom: 2px;
        }

        .activity-time {
          font-size: $font-size-xs;
          color: $text-color-3;
        }
      }

      .activity-arrow {
        color: $text-color-3;
      }
    }
  }
}

.social-energy {
  padding: $spacing-md;

  .energy-card {
    background: $white;
    border-radius: $border-radius-lg;
    padding: $spacing-md;
    box-shadow: $box-shadow-light;

    .energy-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: $spacing-sm;

      h4 {
        font-size: $font-size-md;
        color: $text-color;
      }
    }

    .energy-content {
      margin-bottom: $spacing-md;

      p {
        font-size: $font-size-sm;
        color: $text-color-2;
        line-height: 1.5;
      }
    }

    .energy-actions {
      display: flex;
      gap: $spacing-sm;
    }
  }
}
</style>